/*
 * UDP Client
 * Project 3 
 * Created by: Wilson Burhan & Derrick Mink
 */

import java.io.*;
import java.net.*;
import java.util.Scanner;

/**
 * The UDP echo client program to communicates with the echo server.
 * @author Wilson Burhan & Derrick Mink
 */
public class UDPClient {
	public static void main(String[] args) throws IOException {
		//This part of the code is to specify the port number and the server address.
		String input = null;
		DatagramSocket clientSocket = null;
        System.out.print("Please enter the server address: ");
        Scanner scan = new Scanner(System.in);
        String host = scan.next();
        System.out.print("Please enter the port number: ");
	    int port = scan.nextInt();
	    byte[] sendData = new byte[1024];
	    byte[] receiveData = new byte[1024];
	    InetAddress IPAddress = InetAddress.getByName(host);
        
		try {
			clientSocket = new DatagramSocket();
			DatagramPacket send = new DatagramPacket(sendData, sendData.length, IPAddress, port);
			clientSocket.send(send);
			
        } catch (IOException e) {
            System.err.println("Couldn't connect to the connection: " + host);
            System.exit(0);
        }	
		
		BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
		while (true) {	
			System.out.println("SEND(Type Q or q to Quit)");
			input = inFromUser.readLine();
			if(input.equals("q") || input.equals("Q")) {
				System.out.println("Client has stopped.");
				String err = "The client has been disconnected!";
				sendData = err.getBytes();
				DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
				clientSocket.send(sendPacket);
				clientSocket.close();
				inFromUser.close();
				break;
			}	
			sendData = input.getBytes();
			DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
			clientSocket.send(sendPacket);
			
			DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
			clientSocket.receive(receivePacket);
			input = new String(receivePacket.getData(), 0, receivePacket.getLength());
			System.out.println("RECEIVED: " + input);
			//If the server has been disconnected, ends the program.
			if (input.equals("The connection to the host has been disconnected!")) {
				System.out.println("Client has stopped.");
				clientSocket.close();
				inFromUser.close();
				break;
			}
		}
	}	 
}
